package com.giantlizard.cloud.auth.filter;

import com.giantlizard.cloud.common.security.model.LoginUser;
import com.giantlizard.cloud.common.security.service.TokenService;
import com.giantlizard.cloud.common.security.constants.SecurityConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private static final Logger log = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);

    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        try {
            if (request.getServletPath().equals("/auth/login")) {
                chain.doFilter(request, response);
                return;
            }
            // 获取token
            String token = getTokenFromRequest(request);
            if (StringUtils.hasText(token)) {
                LoginUser loginUser = tokenService.getLoginUser(token);
                if (loginUser != null) {
                    tokenService.verifyToken(loginUser);
                    UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                        loginUser, loginUser.getUserId(), Collections.emptyList());
                    authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authToken);
                }
            }
        } catch (Exception e) {
            log.error("Token认证失败", e);
        }
        chain.doFilter(request, response);
    }

    private String getTokenFromRequest(HttpServletRequest request) {
        String token = request.getHeader(SecurityConstants.AUTHENTICATION);
        if (StringUtils.hasText(token) && token.startsWith(SecurityConstants.PREFIX)) {
            token = token.substring(SecurityConstants.PREFIX.length());
        }
        return token;
    }
} 